import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/cate',
    name: 'cate',
    component: () => import('@/views/Cate'),
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/cart',
    name: 'cart',
    component: () => import('@/views/Cart'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('@/views/User'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/detail/:itemId',
    name: 'detail',
    component: () => import('@/views/Detail'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/itemLists',
    name: 'itemLists',
    component: () => import('@/views/ItemLists'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/addressLists',
    name: 'addressLists',
    component: () => import('@/views/AddressLists'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/addressAdd',
    name: 'addressAdd',
    component: () => import('@/views/AddressAdd'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/addressEdit',
    name: 'addressEdit',
    component: () => import('@/views/AddressEdit'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/Search'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/searchResult',
    name: 'searchResult',
    component: () => import('@/views/SearchResult'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
// 路由前置守卫  登录鉴权
router.beforeEach((to, from, next) => {
  // 判断是否需要登录
  if (to.meta.needLogin) {
    // 需要登录
    // token
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      next({
        name: 'login',
        params: {
          from: to.fullPath
        }
      })
    }
  } else {
    next()
  }
})

export default router
